package nz.ac.massey.webtech.servlets.xml;

import javax.servlet.*;
import javax.servlet.http.*;
import org.jdom.*;
import org.jdom.transform.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.*;
/**
 * Abstract catalog servlet class. Rendering is done in subclasses.
 * @author  Jens Dietrich   
 * @version 1.0
 */
public abstract class AbstractCatalogServlet extends HttpServlet {
    
    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
    }
    
    /** Destroys the servlet.
     */
    public void destroy() {
        
    }
    // Get the URL of the stylesheet.
    protected abstract String getStylesheetUrl();
    
    // Get the content type.
    protected abstract String getContentType();
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        try {
            Document doc = (new SQL2XML()).query();
            response.setContentType(getContentType());
            java.io.PrintWriter out = response.getWriter();
            
            // Transform XML with XSL stylesheet
            InputStream xslin = getClass().getResourceAsStream(getStylesheetUrl());
            Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xslin));
            transformer.transform(new JDOMSource(doc), new StreamResult(out));
            
            out.close();
        }
        catch (Exception x) {
            this.getServletContext().log(x,"cannot read db");
            x.printStackTrace();
            // we should output some html here ...
        }
    }
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    
}
